<template>
  <div>
    <nav v-text="name"></nav>
    <show-msg ref="show" :message="msgList" />
    <show-input @send="handleWsSend" />
    <back />
  </div>
</template>

<script>
import Back from "@/components/Back/Back";
import ShowInput from "./Input.vue";
import ShowMsg from "./ShowMsg.vue";
const ws = new WebSocket("ws://127.0.0.1:4000");
// const ws = new WebSocket("ws://192.168.43.48:4000");

export default {
  components: { ShowMsg, ShowInput, Back },
  name: "",
  data() {
    return {   
      msgList: []
    };
  },
  computed: {
    _id() {
      return this.$store.getters.user._id || JSON.parse(localStorage.getItem('userInfo'))._id;
    },
    userInfo(){
      return this.$store.getters.user || JSON.parse(localStorage.getItem('userInfo'))
    },
    friendId(){
      return this.$route.params.uid 
    },
    name(){
      return this.friendId == 1?'多人聊天':this.friendId
    },
    type(){
      return this.$route.params.type
    }
  },
  mounted() {
    ws.addEventListener("open", this.handleWsOpen.bind(this), false);
    ws.addEventListener("close", this.handleWsClose.bind(this), false);
    ws.addEventListener("error", this.handleWsError.bind(this), false);
    ws.addEventListener("message", this.handleWsMessage.bind(this), false);
  },
  methods: {
    handleWsSend(msg) {
      if(this.type==1){
        ws.send(
        JSON.stringify({
          send_id: this._id,
          msgType: 1,//群聊消息类型
          nickname: this.userInfo.nickname,
          avatar: this.userInfo.avatar,
          dateTime: new Date().getDate(),
          msg: msg
        })
      );
      }else{
        ws.send(
          JSON.stringify({
            msgType:2,
            send_id:this._id,
            receive_id:this.friendId,
            nickname: this.userInfo.nickname,
          avatar: this.userInfo.avatar,
          dateTime: new Date().getDate(),
            msg:msg
          })
        )
      }
    },
    handleWsOpen(e) {
      ws.send(
        JSON.stringify({
          id:this._id,
          msgType: 0, //用户连接时发送id到服务器
        })
      )
      console.log("FE:WebSocket open", e);
    },
    handleWsClose(e) {
      console.log("FE:WebSocket close", e);
    },
    handleWsError(e) {
      console.log("FE:WebSocket error", e);
    },
    handleWsMessage(e) {
      const msg = JSON.parse(e.data);
      this.msgList.push(msg);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
nav {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  background-color: aqua;
  text-align: center;
  height: 48px;
  line-height: 44px;
  z-index: 10;
}
</style>
